#include <malloc.h>
#include "stdafx.h"

#pragma data_seg(".SHRDATA")
TCHAR s_tFiles[APP_COUNT][MAX_PATH] = {{NULL}};
int s_uIndices[APP_COUNT] = {0};
size_t s_uCount = 0;
#pragma data_seg()

void InitFromFile(TCHAR *file)
{
	FILE *fp = _tfopen(file, _T("rb"));
	if (!fp)
		return;

	LogHeader header;
	fread(&header, sizeof(LogHeader), 1, fp);
	fread(s_tFiles, MAX_PATH * header.encoding, APP_COUNT, fp);
	fclose(fp);

	// sort.
	while (s_tFiles[s_uCount++][0]);
	s_uCount--;
	for (size_t i=0; i<s_uCount; i++)
		s_uIndices[i] = i;
	for (size_t i=0; i<s_uCount; i++)
	{
		int min = i;
		for (size_t j=i+1; j<s_uCount; j++)
		{
			if (lstrcmpi(s_tFiles[s_uIndices[j]], s_tFiles[s_uIndices[min]]) < 0)
			{
				min = j;
			}
		}
		int tmp = s_uIndices[i];
		s_uIndices[i] = s_uIndices[min];
		s_uIndices[min] = tmp;
	}
}

void SaveToFile(TCHAR *file)
{
	FILE *fp = _tfopen(file, _T("rb+"));
	if (!fp)
		return;

	fseek(fp, sizeof(LogHeader), SEEK_SET);
	fwrite((const void *)s_tFiles, MAX_PATH * sizeof(TCHAR), APP_COUNT, fp);
	fclose(fp);
}

void ClearFileList()
{
	ZeroMemory(s_tFiles, APP_COUNT * MAX_PATH * sizeof(TCHAR));
	ZeroMemory(s_uIndices, APP_COUNT * sizeof(int));
}

int GetIndex(TCHAR *file)
{
	if (file == NULL)
		return -1;

	// 1.binary search
	int start = 0;
	int end = s_uCount - 1;
	int pilot = 0;
	int ret = 0;
	while (start <= end)
	{
		pilot = (start + end)/2;
		ret = lstrcmpi(file, s_tFiles[s_uIndices[pilot]]);
		if ( ret > 0)
		{
			start = pilot + 1;
		}
		else if (ret < 0)
		{
			end = pilot - 1;
		}
		else
		{
			return s_uIndices[pilot];
		}
	}

	// 2.insert
	if (s_uCount == APP_COUNT)
		return -1;
	for(int i=s_uCount; i>pilot; i--)
        s_uIndices[i] = s_uIndices[i-1];
	int index = pilot;
	if (ret > 0)
	{
		index++;
	}
	lstrcpy(s_tFiles[s_uCount], file);
    s_uIndices[index] = s_uCount++;

	return s_uIndices[index];
}
